package com.xzcedu.mhl.service;

import com.xzcedu.mhl.dao.BillDAO;
import com.xzcedu.mhl.dao.MenuDAO;
import com.xzcedu.mhl.dao.MultiTableDAO;
import com.xzcedu.mhl.domain.Bill;
import com.xzcedu.mhl.domain.Menu;
import com.xzcedu.mhl.domain.MultiTableBean;

import java.util.List;
import java.util.UUID;

/**
 * @author 徐州城
 * @version 1.0
 * 处理和账单相关的业务逻辑
 */
public class BillService {
    //定义BillDAO属性
    BillDAO billDAO = new BillDAO();
    //定义MenuService属性
    private MenuService menuService = new MenuService();
    //定义DiningTableService
    private DiningTableService diningTableService = new DiningTableService();

    private MultiTableDAO multiTableDAO = new MultiTableDAO();

    //编写点餐方法
    //1. 生成账单
    //2. 需要更新对应餐桌的状态
    //3. 如果插入成功，返回true
    public boolean orderMenu(int menuId, int nums, int diningTableId) {
        //生成一个账单号
        String billID = UUID.randomUUID().toString();

        //得到金额
        Menu menu = menuService.getMenuById(menuId);

        //将账单生成到bill表，要求直接计算账单金额
        int update = billDAO.update("insert into bill values(null, ?, ?, ?, ?, ?, now(), '未结账')",
                billID, menuId, nums, (menu.getPrice() * nums), diningTableId);

        if (!(update > 0)) {
            return false;
        }

        return diningTableService.updateDiningTableState(diningTableId, "就餐中");
    }

    //返回所有的账单，返回给View，并按照id 升序
    public List<Bill> getAllBill(){
        return billDAO.queryMultiply("select * from bill order by diningTableId", Bill.class);
    }

    //返回所有账单并带有菜品名，返回给View，并按照id 升序
    public List<MultiTableBean> getAllBill02(){
        return multiTableDAO.queryMultiply(
                "SELECT bill.*,menu.`name` as name2,menu.price FROM menu,bill WHERE menu.`id` = bill.`menuId` order by bill.diningTableId", MultiTableBean.class);
    }

    //查看某个餐桌是否有未结账的账单
    public boolean hasPayBillByDiningTableId(int diningTableId){
        Bill bill =
                billDAO.querySingle("SELECT * FROM bill WHERE diningTableId=? AND state = '未结账' LIMIT 0,1", Bill.class, diningTableId);
        return bill != null;//如果bill不为空返回t，为空则为f
    }

    //完成结账[如果餐桌存在，并且该餐桌有未结账的账单]
    public boolean payBill(int diningTableId, String payMode) {

        //如果这里使用事务的话，需要使用ThreadLocal来解决，框架中比如mybatis 提供了事务支持
        //1. 修改bill表
        int update = billDAO.update("update bill set state=? where diningTableId=? and state='未结账'", payMode, diningTableId);
        if (update <= 0) { //该语句执行，说明update语句没有影响表
            return false;
        }

        //2. 修改diningTable表的state
        //注意: 不要直接在这里操作，而应该调用DiningTableService 方法，完成更新
        return diningTableService.updateDiningTableToState(diningTableId, "空");
    }
}
